import { useState } from 'react';
import { Button, Menu, Dropdown, Typography, Tooltip, Popconfirm, Modal, message, Popover } from 'antd';
import CommonTable from '@/components/CommonTable';
import CommonGoodsImg from '@/components/CommonGoodsImg';
import CommonLoading from '@/components/CommonLoading';
import { formatAmount } from '@/utils/utils.jsx';
import { vipPriceReApplyOp, changePriceAuditOp, customAuditPassOp, customAuditRefuseOp } from '../service';
import styles from '../index.module.less'
import RelativeModal from './RelativeModal';

const { Paragraph } = Typography;

//使用中  审核失败
export default ({ type, status, data, updateList, openApplyModal }) => {

  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);

  const baseColumns = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 60,
      render:(t, r, i) => i + 1
    },
    {
      title: '供应商',
      dataIndex: 'storeName',
      key: 'storeName',
      width: 120,
      render: function (text, record) {
        return {
          children:<span className='common-color3' style={{ fontWeight:500 }}>{text}</span>,
          props: {
            rowSpan: record.rowSpan_spu,
          },
        };
      },
    },
    {
      title: '商品',
      dataIndex: 'commonGoodsName',
      key: 'commonGoodsName',
      width: 280,
      render:  (text, record) =>{
        return {
        children: <div className="flex" style={{ margin: '5px 0' }}>
         <CommonGoodsImg
            img={record.goodsImage}
            storeId={record.zjfStorePk || record.storeId}
            goodsId={record.goodsId || record.goodsPriceVerifyVos[0].zjfGoodsPk}
            size="48x48"
            width='48'
          />
        <div style={{ marginLeft: '8px', display:'flex', justifyContent:"center", alignItems:'center' }}>
          <Tooltip title={type == 6 ? record.goodsName : record.commonGoodsName}>
            <Paragraph ellipsis={{ rows: 2 }} style={{ margin: 0 }}>
              <span className='common-color4'>{type == 6 ? record.goodsName : record.commonGoodsName}</span>
            </Paragraph>
          </Tooltip>
        </div>
      </div>,
          props: {
            rowSpan: record.rowSpan_spu,
          },
        };
      }
    },
  ]

  const applyTimeColumn = [
    {
      title: '申请时间',
      dataIndex: 'addTime',
      key: 'addTime',
      width: 160,
      render:text => <span className='common-color4'>{text}</span>
    },
  ]

  const columns = [
    ...baseColumns ,
    {
      title: '尺码/规格',
      dataIndex: 'size',
      key: 'size',
      width: 220,
      render: function (text, record) {
        return {
          children: <span className='common-color4'>{text}</span>,
          props: {
            rowSpan: record.rowSpan_sku,
          },
        };
      },
    },
    {
      title: '颜色',
      dataIndex: 'name1',
      key: 'name1',
      width: 120,
      render: (text, { colors = [] }) => {
        if (colors.length > 1) {
          const menu = (
            <Menu>
              {colors.map((item) => (
                <Menu.Item key={item}>{item}</Menu.Item>
              ))}
            </Menu>
          );
          return (
            <Dropdown
              overlay={menu}
              placement="bottomCenter"
              overlayClassName={styles.dropdown}
            >
              <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>同价格颜色({colors.length})</a>
            </Dropdown>
          );
        }
        return colors[0];
      },
    },
    //770
    {
      title: ()=>type == 5 ? '拿货金额' : '商城价',
      dataIndex: 'goodPrice',
      key: 'goodPrice',
      width: 125,
      render:text=> <span className='common-color9' style={{ fontWeight:500 }}>￥{formatAmount(text)}</span>
    },
    {
      title: '会员价',
      dataIndex: 'vipPrice',
      key: 'vipPrice',
      width: 125,
      render:text=> <span className='common-color9' style={{ fontWeight:500 }}>￥{formatAmount(text)}</span>
    }
  ];

  const judgeColumnsFunc = () => {
     if (type == '2') {//使用中 
       return [ 
         ...columns,
         ...applyTimeColumn,
        {
        title: '审核时间',
        dataIndex: 'verifyTime',
        key: 'verifyTime',
        width: 160,
        render:text => <span className='common-color4'>{text}</span>
      }]
     } else if(type == '1') {//待审核
        return [ 
          ...columns,
          ...applyTimeColumn,
        ]
     } else if (type == '3') {//审核失败
      return [ 
        ...columns,
        ...applyTimeColumn,
      {
        title: '审核时间',
        dataIndex: 'verifyTime',
        key: 'verifyTime',
        width: 160,
        render:text => <span className='common-color4'>{text}</span>
      },
      {
        title: '审核失败原因',
        dataIndex: 'verifyFailCause',
        key: 'verifyFailCause',
        width: 200,
        render:text => <span className='common-color4'>{text}</span>
      }
    ]
     } else if (type == '4'){//已作废
      return [ 
        ...columns,
        ...applyTimeColumn,
      {
        title: '审核时间',
        dataIndex: 'verifyTime',
        key: 'verifyTime',
        width: 160,
        render:text => <span className='common-color4'>{text}</span>
      },
      {
        title: '操作',
        fixed: 'right',
        align:"center",
        width: 100,
        render: function (text, record) {
          return (
            <Popconfirm title="确定重新申请?" onConfirm={() => reApply(record)}>
              <Button type="link">重新申请</Button>
            </Popconfirm>
          );
        },
      },
    ]
     }else if(type == 5){
       return [
        ...columns,
        {
          title: '操作',
          fixed: 'right',
          align:"center",
          dataIndex:'vipPriceIds',
          width: 100,
          render: text => {
            return (
              <span className="opera-span-common">
                <a onClick={() => handleConfim(2, text)}>通过</a>
                <span> | </span>
                <a onClick={() => handleConfim(3, text)}>拒绝</a>
              </span>
            );
          },
        },
       ]
     }else if(type == 6){
       return [
        ...baseColumns,
        {
          title: '拿货金额',
          dataIndex: 'takePrice',
          key: 'takePrice',
          width: 125,
          render:text=> <span className='common-color9' style={{ fontWeight:500 }}>￥{formatAmount(text)}</span>
        },
        {
          title: '变更后会员价',
          dataIndex: 'vipPrice',
          key: 'vipPrice',
          width: 125,
          render:text=> <span className='common-color9' style={{ fontWeight:500 }}>￥{formatAmount(text)}</span>
        },
        {
          title: '拿货员',
          dataIndex: 'deliverymanUserName',
          key: 'taskUserName',
          width: 125,
        },
        {
          title: '发起人',
          dataIndex: 'taskUserName',
          key: 'taskUserName',
          width: 125,
          render:(text, record) => <span className='common-color4'>{text}{record.taskShortName ? <p>{record.taskShortName}</p> : ''}</span>
        },
        {
          title: '审核人',
          dataIndex: 'auditUserName',
          key: 'auditUserName',
          width: 125,
          render:(text, record) => <span className='common-color4'>{text}{record.auditShortName ? <p>{record.auditShortName}</p> : ''}</span>
        },
        {
          title: '审核时间',
          dataIndex: 'auditTime',
          key: 'auditTime',
          width: 160,
          render:text => <span className='common-color4'>{text}</span>
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          width: 160,
          render:text => <span className='common-color9'>{text == 1 ? '使用中' : '审核失败'}</span>
        },
        {
          title: '操作',
          fixed: 'right',
          align:"center",
          dataIndex: 'id',
          key: 'id',
          width: 100,
          render: (text, record) => record.status == 1 && <Button type="link" onClick={()=>setVisible(text)}>关联单据号</Button>,
        },
       ]
     } else if(type == 7) {
        return [
            {
              title: '序号',
              dataIndex: 'index',
              width: 60,
              render:(t, r, i) => i + 1
            },
            {
                title: '供应商',
                dataIndex: 'storeName',
                key: 'storeName',
                width: 120,
                render: function (text, record) {
                  return {
                    children:<span className='common-color3 table-weight-text'>{text}</span>,
                    props: {
                      rowSpan: record.rowSpan_spu,
                    },
                  };
                },
              },
              {
                title: '商品',
                dataIndex: 'commonGoodsName',
                key: 'commonGoodsName',
                width: 280,
                render:  (text, record) =>{
                  return (
                    <div className='flex'>
                    <img
                      src={record.imageUrl}
                      alt=""
                      className={styles.imgWrap}
                    />
                    <div style={{ display: 'flex' }}>
                      <Popover
                        content={(<div className='custom-ant-popver-content'>
                          <div>{record.goodsName}</div>
                          <div>{record.skuName}</div>
                        </div>)}
                      >
                        <div>
                          <div className='textOverflowMultiOne'>{record.goodsName}</div>
                          <div className='textOverflowMultiOne'>{record.skuName}</div>
                        </div>
                      </Popover>
                    </div>
                  </div>
                  )
                }
              },
              {
                title: "商品编码",
                dataIndex: "outStoreSku",
                width: 140,
                render: text => (
                  <span className="table-weight-text">{text}</span>
                )
              },
              {
                title: "款式编码",
                dataIndex: "outStoreSpu",
                width: 140,
                render: text => (
                  <span className="table-weight-text">{text}</span>
                )
              },
            {
              title: '拿货金额',
              dataIndex: 'takePrice',
              key: 'takePrice',
              width: 125,
              render:text=> <span className='common-color9' style={{ fontWeight:500 }}>￥{formatAmount(text)}</span>
            },
            {
              title: '变更后拿货金额',
              dataIndex: 'changePrice',
              key: 'changePrice',
              width: 125,
              render:text=> <span className='common-color9' style={{ fontWeight:500 }}>￥{formatAmount(text)}</span>
            },
            {
              title: '拿货员',
              dataIndex: 'deliverymanUserName',
              key: 'taskUserName',
              width: 125,
            },
            {
              title: '发起人',
              dataIndex: 'taskUserName',
              key: 'taskUserName',
              width: 125,
              render:(text, record) => <span className='common-color4'>{text}{record.taskShortName ? <p>{record.taskShortName}</p> : ''}</span>
            },
            {
              title: '生成时间',
              dataIndex: 'createTime',
              key: 'createTime',
              width: 160,
              render:text => <span className='common-color4'>{text}</span>
            },
            {
              title: '操作',
              fixed: 'right',
              align:"center",
              dataIndex: 'id',
              key: 'id',
              width: 100,
              render: (text, record) => <Button type="link" onClick={()=>setVisible(text)}>关联单据号</Button>,
            },
           ]
     }else if(type == 8){
      const baseArr = [
        {
          title: '供应商',
          dataIndex: 'storeName',
          key: 'storeName',
          width: 120,
          render: (text)=><span className='common-color3' style={{ fontWeight:500 }}>{text}</span>
        },
        {
            title: '商品类别',
            dataIndex: 'platType',
            key: 'platType',
            width: 120,
            render: (text)=><span className='common-color3' style={{ fontWeight:500 }}>{text && text == 1 ? '系统商品': '网店商品'}</span>
          },
        {
          title: '商品',
          dataIndex: 'commonGoodsName',
          key: 'commonGoodsName',
          width: 280,
          render: (text, record) => {
            const showStr = `【${record.storeName}】${record.name} ${record.spec}`
            return (<div className="flex" style={{ margin: '5px 0' }}>
            <CommonGoodsImg
              img={record.image}
              storeId={record.storeId}
              goodsId={record.goodsId}
              size="48x48"
              width='48'
            />
            <div style={{ marginLeft: '8px', display: 'flex', justifyContent: "center", alignItems: 'center' }}>
              <Tooltip title={showStr}>
                <Paragraph ellipsis={{ rows: 2 }} style={{ margin: 0 }}>
                  <span className='common-color4'>{showStr}</span>
                </Paragraph>
              </Tooltip>
            </div>
          </div>)
          }
        },
        {
          title: '商品编码',
          dataIndex: 'outStoreSku',
          key: 'outStoreSku',
          width: 100,
          render:text => <span className='common-color4'>{text}</span>
        },
        {
          title: '拿货金额',
          dataIndex: 'price',
          key: 'price',
          width: 120,
          render:text=> <span className='common-color9' style={{ fontWeight:500 }}>￥{formatAmount(text)}</span>
        },
        {
          title: '申请改价金额',
          dataIndex: 'applyPrice',
          key: 'applyPrice',
          width: 120,
          render:text=> <span className='common-color9' style={{ fontWeight:500 }}>￥{formatAmount(text)}</span>
        },
        {
          title: '申请时间',
          dataIndex: 'applyTime',
          key: 'applyTime',
          width: 130,
          render:text => <span className='common-color4'>{text}</span>
        },
      ]
      if(status == 5){
        return [
          ...baseArr,
          {
            title: '操作',
            fixed: 'right',
            align:"center",
            dataIndex:'id',
            width: 80,
            render: text => {
              return (
                <span className="opera-span-common">
                  <a onClick={() => handleConfim(2, text, 'pass')}>通过</a>
                  <span> | </span>
                  <a onClick={() => handleConfim(3, text, 'refuse')}>拒绝</a>
                </span>
              );
            },
          },
        ]
      }else{
        return [
          ...baseArr,
          {
            title: '审核时间',
            dataIndex: 'auditTime',
            key: 'auditTime',
            width: 130,
            render:text => <span className='common-color4'>{text}</span>
          },
          {
            title: '审核人',
            dataIndex: 'auditor',
            key: 'auditor',
            width: 130,
            render:text => <span className='common-color4'>{text}</span>
          },
          {
            title: '审核状态',
            dataIndex: 'state',
            key: 'state',
            width: 80,
            render:text => <span className='common-color4'>{text == 2 ? '通过' : '拒绝'}</span>
          },
        ]
      }
      
     }
  }

  //confirm 
const handleConfim =  (status, ids, type) => {
  Modal.confirm({
    className: "views-modal-confirm",
    centered: true,
    title: '改价审核',
    content: `请确认是否${status == 2 ? '通过' : '拒绝'}审核`,
    onOk () {
      dealAudit(status, ids, type)
    }
  })
}

//改价审核操作
const dealAudit = async (status, ids, type) => {
  setLoading(true)
  let res;
  if(type == 'pass'){
    res = await customAuditPassOp({ id: ids});
  }else if (type == 'refuse'){
    res = await customAuditRefuseOp([ids]);
  }else{
    res = await changePriceAuditOp({ status, ids });
  }
  const { success, msg = '操作成功' } = res || {};
  if(success){
    updateList()
    message.success(msg)
  }
  setLoading(false)
}

// 重新申请
const reApply = async (record) => {
  const arr=[]
  record.goodsPriceVerifyVos && record.goodsPriceVerifyVos.map(item=>{//format 参数
    const { goodPrice, goodsState, zjfGoodsCommonPk, zjfGoodsPk, zjfStorePk } = item
    arr.push({ goodPrice, goodsState, zjfGoodsCommonPk, zjfGoodsPk, zjfStorePk })
  })
  const { success } = await vipPriceReApplyOp(arr)
  if(success){
    message.success('已添加至待申请列表')
    openApplyModal()
  }
};

  const TableProps = {
    data,
    columns:judgeColumnsFunc(),
    scroll: { x: 1360, y: 630 },
    handelRowKey(record){
      if(type == 6 || type ==7){
        return record.id
      }else{
        return record.vipPriceIds + record.size + record.colors
      }
    }
  };

  //关联弹窗props
  const RelativeModalProps = {
    type,
    visible,
    handleClose(){
      setVisible(false)
    }
  }

  return <>
    <CommonTable { ...TableProps } />
    <RelativeModal { ...RelativeModalProps }/>
    <CommonLoading loading={loading} />
  </>
};

